package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.ICaseContractService;
import com.mdd.admin.validate.CaseContractCreateValidate;
import com.mdd.admin.validate.CaseContractSearchValidate;
import com.mdd.admin.validate.CaseContractUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.CaseContractDetailVo;
import com.mdd.admin.vo.CaseContractListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.CaseContract;
import com.mdd.common.mapper.CaseContractMapper;
import com.mdd.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 新建合同案件信息实现类
 * @author LikeAdmin
 */
@Service
public class CaseContractServiceImpl implements ICaseContractService {
        
    @Resource
    CaseContractMapper caseContractMapper;

    /**
     * 新建合同案件信息列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<CaseContractListedVo>
     */
    @Override
    public PageResult<CaseContractListedVo> list(PageValidate pageValidate, CaseContractSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<CaseContract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        caseContractMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:caseName@case_name:str",
            "=:caseType@case_type:str",
            "=:businessType@business_type:str",
            "=:putinType@putin_type:str",
            "=:undertakingDepartment@undertaking_department:str",
            "=:conductor:str",
            "=:taxRate@tax_rate:str",
            "=:costType@cost_type:str",
            "=:cost:str",
            "=:contributionPool@contribution_pool:str",
            "=:ownershipDistribution@ownership_distribution:str",
            "=:haveCase@have_case:str",
            "=:designatedCountry@designated_country:str",
            "=:brandType@brand_type:str",
            "=:classQuantity@class_quantity:long",
            "=:quantity:long",
            "=:officialFee@official_fee:str",
            "=:agencyFee@agency_fee:str",
            "=:hirdPartyPayment@hird_party_payment:str",
            "=:signedAmount@Signed_amount:str",
            "=:invoiceValue@invoice_value:str",
            "=:fundsReceived@funds_received:str",
            "between:paidupDate@paidup_date:str",
            "=:planNumber@plan_number:str",
            "=:caseStatus@case_status:str",
            "=:caseLink@case_link:str",
            "=:remark:str",
            "=:caseNameid@case_nameid:long",
            "=:businessTypeid@business_typeid:long",
            "=:undertakingDepartmentid@Undertaking_departmentid:long",
            "=:ownershipDistributionid@ownership_distributionid:long",
            "=:costTypeid@cost_typeid:long",
            "=:correlationTypeid@correlation_typeid:long",
            "=:isRegister@is_register:str",
            "=:isInvalid@is_invalid:str",
            "=:isExistingcase@is_existingcase:str",
            "=:isPapernotice@is_papernotice:str",
            "=:customerDocumentNumber@customer_document_number:str",
            "=:copyrightType@copyright_type:str",
            "=:caseFlow@case_flow:str",
            "=:countryOfOrigin@country_of_origin:str",
            "=:agency:str",
            "=:proposalForm@proposal_form:str",
            "=:isMaterials@is_materials:str",
            "=:isFund@is_fund:str",
            "=:initialPeriod@initial_period:str",
            "=:referenceNumber@reference_number:str",
            "=:contractNumber@contract_number:str",
            "=:budget:str",
            "=:author:str",
            "=:homeLocation@home_location:str",
            "=:softwareAbbreviation@software_abbreviation:str",
            "=:versionNumber@version_number:str",
            "=:softwareWorkDescription@software_work_description:str",
            "between:developmentCompletionDate@development_completion_date:str",
            "=:publishedStatus@published_status:str",
            "=:hardwareEnvironment@hardware_environment:str",
            "=:softwareEnvironment@software_environment:str",
            "=:programmingLanguage@programming_language:str",
            "=:sourceQuantity@source_quantity:str",
            "=:functionAndArt@function_and_art:str",
            "=:handlingInformation@handling_information:str",
            "between:principalDates@principal_dates:str",
            "between:customerTerm@customer_term:str",
            "between:internalWearLife@internal_wear_life:str",
            "=:isStateCompensation@is_state_compensation:str",
            "=:click:str",
            "=:partOwner@part_owner:str",
            "=:todonote@todoNote:str",
            "between:manageDate@manage_date:str",
            "=:countType@count_type:str",
            "=:numberOfPoints@number_of_points:str",
            "=:addtotalstatepoint:str",
            "between:royaltyDate@royalty_date:str",
            "=:workPoints@work_points:str",
            "=:creator:str",
            "=:chargeType@charge_type:str",
            "=:currency:str",
            "=:sum:str",
            "between:advancePaymentDate@advance_payment_date:str",
            "=:paymentRequestNumber@payment_request_number:str",
            "between:requestedDate@requested_date:str",
            "between:accountsDate@accounts_date:str",
            "=:invoiceNumber@invoice_number:str",
            "like:chargeName@charge_name:str",
            "=:chargeDepict@charge_depict:str",
            "=:chargeDepictfine@charge_depictfine:str",
            "=:extendedAmount@extended_amount:str",
            "=:discountRate@discount_rate:str",
            "=:count:str",
            "=:parities:str",
            "=:collectingCompanyAccount@collecting_company_account:str",
            "=:collectionStatus@collection_status:str",
            "=:accountDetails@account_details:str",
            "between:slt:str",
            "=:externalBillingNumber@external_billing_number:str",
            "between:externalBillingDate@external_billing_date:str",
            "=:beddingCondition@bedding_condition:str",
            "=:handOver@hand_over:str",
            "=:expenseNote@expense_note:str",
            "=:reductionType@reduction_type:str",
            "=:actualCurrency@actual_currency:str",
            "between:officialDeadline@official_deadline:str",
            "=:ourRef@our_ref:str",
            "like:relevantCaseName@relevant_case_name:str",
            "=:correlationType@correlation_type:str",
            "=:userId@user_id:long",
            "like:userName@user_name:str",
            "=:updateUserId@update_user_id:long",
            "like:updateUserName@update_user_name:str",
        });

        IPage<CaseContract> iPage = caseContractMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<CaseContractListedVo> list = new LinkedList<>();
        for(CaseContract item : iPage.getRecords()) {
            CaseContractListedVo vo = new CaseContractListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 新建合同案件信息详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return CaseContract
     */
    @Override
    public CaseContractDetailVo detail(Integer id) {
        CaseContract model = caseContractMapper.selectOne(
                new QueryWrapper<CaseContract>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        CaseContractDetailVo vo = new CaseContractDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 新建合同案件信息新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(CaseContractCreateValidate createValidate) {
        CaseContract model = new CaseContract();

        model.setCaseName(createValidate.getCaseName());
        model.setCaseType(createValidate.getCaseType());
        model.setBusinessType(createValidate.getBusinessType());
        model.setPutinType(createValidate.getPutinType());
        model.setUndertakingDepartment(createValidate.getUndertakingDepartment());
        model.setConductor(createValidate.getConductor());
        model.setTaxRate(createValidate.getTaxRate());
        model.setCostType(createValidate.getCostType());
        model.setCost(createValidate.getCost());
        model.setContributionPool(createValidate.getContributionPool());
        model.setOwnershipDistribution(createValidate.getOwnershipDistribution());
        model.setHaveCase(createValidate.getHaveCase());
        model.setDesignatedCountry(createValidate.getDesignatedCountry());
        model.setBrandType(createValidate.getBrandType());
        model.setClassQuantity(createValidate.getClassQuantity());
        model.setQuantity(createValidate.getQuantity());
        model.setOfficialFee(createValidate.getOfficialFee());
        model.setAgencyFee(createValidate.getAgencyFee());
        model.setHirdPartyPayment(createValidate.getHirdPartyPayment());
        model.setSignedAmount(createValidate.getSignedAmount());
        model.setInvoiceValue(createValidate.getInvoiceValue());
        model.setFundsReceived(createValidate.getFundsReceived());
        model.setPaidupDate(createValidate.getPaidupDate());
        model.setPlanNumber(createValidate.getPlanNumber());
        model.setCaseStatus(createValidate.getCaseStatus());
        model.setCaseLink(createValidate.getCaseLink());
        model.setRemark(createValidate.getRemark());
        model.setCaseNameid(createValidate.getCaseNameid());
        model.setBusinessTypeid(createValidate.getBusinessTypeid());
        model.setUndertakingDepartmentid(createValidate.getUndertakingDepartmentid());
        model.setOwnershipDistributionid(createValidate.getOwnershipDistributionid());
        model.setCostTypeid(createValidate.getCostTypeid());
        model.setCorrelationTypeid(createValidate.getCorrelationTypeid());

        // 非空判断
        if (!"".equals(createValidate.getIsRegister()) && createValidate.getIsRegister() != null)
            model.setIsRegister(createValidate.getIsRegister());
        if (!"".equals(createValidate.getIsInvalid()) && createValidate.getIsInvalid() != null)
            model.setIsInvalid(createValidate.getIsInvalid());
        if (!"".equals(createValidate.getIsExistingcase()) && createValidate.getIsExistingcase() != null)
            model.setIsExistingcase(createValidate.getIsExistingcase());
        if (!"".equals(createValidate.getIsPapernotice()) && createValidate.getIsPapernotice() != null)
            model.setIsPapernotice(createValidate.getIsPapernotice());

        model.setCustomerDocumentNumber(createValidate.getCustomerDocumentNumber());
        model.setCopyrightType(createValidate.getCopyrightType());
        model.setCaseFlow(createValidate.getCaseFlow());
        model.setCountryOfOrigin(createValidate.getCountryOfOrigin());
        model.setAgency(createValidate.getAgency());
        model.setProposalForm(createValidate.getProposalForm());
        model.setIsMaterials(createValidate.getIsMaterials());
        model.setIsFund(createValidate.getIsFund());
        model.setInitialPeriod(createValidate.getInitialPeriod());
        model.setReferenceNumber(createValidate.getReferenceNumber());
        model.setContractNumber(createValidate.getContractNumber());
        model.setBudget(createValidate.getBudget());
        model.setAuthor(createValidate.getAuthor());
        model.setHomeLocation(createValidate.getHomeLocation());
        model.setSoftwareAbbreviation(createValidate.getSoftwareAbbreviation());
        model.setVersionNumber(createValidate.getVersionNumber());
        model.setSoftwareWorkDescription(createValidate.getSoftwareWorkDescription());
        model.setDevelopmentCompletionDate(createValidate.getDevelopmentCompletionDate());
        model.setPublishedStatus(createValidate.getPublishedStatus());
        model.setHardwareEnvironment(createValidate.getHardwareEnvironment());
        model.setSoftwareEnvironment(createValidate.getSoftwareEnvironment());
        model.setProgrammingLanguage(createValidate.getProgrammingLanguage());
        model.setSourceQuantity(createValidate.getSourceQuantity());
        model.setFunctionAndArt(createValidate.getFunctionAndArt());
        model.setHandlingInformation(createValidate.getHandlingInformation());
        model.setPrincipalDates(createValidate.getPrincipalDates());
        model.setCustomerTerm(createValidate.getCustomerTerm());
        model.setInternalWearLife(createValidate.getInternalWearLife());
        model.setIsStateCompensation(createValidate.getIsStateCompensation());
        model.setClick(createValidate.getClick());
        model.setPartOwner(createValidate.getPartOwner());
        model.setTodonote(createValidate.getTodonote());
        model.setManageDate(createValidate.getManageDate());
        model.setCountType(createValidate.getCountType());
        model.setNumberOfPoints(createValidate.getNumberOfPoints());
        model.setAddtotalstatepoint(createValidate.getAddtotalstatepoint());
        model.setRoyaltyDate(createValidate.getRoyaltyDate());
        model.setWorkPoints(createValidate.getWorkPoints());
        model.setCreator(createValidate.getCreator());
        model.setChargeType(createValidate.getChargeType());
        model.setCurrency(createValidate.getCurrency());
        model.setSum(createValidate.getSum());
        model.setAdvancePaymentDate(createValidate.getAdvancePaymentDate());
        model.setPaymentRequestNumber(createValidate.getPaymentRequestNumber());
        model.setRequestedDate(createValidate.getRequestedDate());
        model.setAccountsDate(createValidate.getAccountsDate());
        model.setInvoiceNumber(createValidate.getInvoiceNumber());
        model.setChargeName(createValidate.getChargeName());
        model.setChargeDepict(createValidate.getChargeDepict());
        model.setChargeDepictfine(createValidate.getChargeDepictfine());
        model.setExtendedAmount(createValidate.getExtendedAmount());
        model.setDiscountRate(createValidate.getDiscountRate());
        model.setCount(createValidate.getCount());
        model.setParities(createValidate.getParities());
        model.setCollectingCompanyAccount(createValidate.getCollectingCompanyAccount());
        model.setCollectionStatus(createValidate.getCollectionStatus());
        model.setAccountDetails(createValidate.getAccountDetails());
        model.setSlt(createValidate.getSlt());
        model.setExternalBillingNumber(createValidate.getExternalBillingNumber());
        model.setExternalBillingDate(createValidate.getExternalBillingDate());
        model.setBeddingCondition(createValidate.getBeddingCondition());
        model.setHandOver(createValidate.getHandOver());
        model.setExpenseNote(createValidate.getExpenseNote());
        model.setReductionType(createValidate.getReductionType());
        model.setActualCurrency(createValidate.getActualCurrency());
        model.setOfficialDeadline(createValidate.getOfficialDeadline());
        model.setOurRef(createValidate.getOurRef());
        model.setRelevantCaseName(createValidate.getRelevantCaseName());
        model.setCorrelationType(createValidate.getCorrelationType());

        // 设置 操作人信息 以及 创建时间
        model.setUserId(Long.valueOf(LikeAdminThreadLocal.getAdminId()));
        model.setUserName(LikeAdminThreadLocal.get("username").toString());
        model.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        model.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        model.setIsDelete(0);

        caseContractMapper.insert(model);
    }

    /**
     * 新建合同案件信息编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(CaseContractUpdateValidate updateValidate) {
        CaseContract model = caseContractMapper.selectOne(
                new QueryWrapper<CaseContract>()
                    .eq("id",  updateValidate.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setCaseName(updateValidate.getCaseName());
        model.setCaseType(updateValidate.getCaseType());
        model.setBusinessType(updateValidate.getBusinessType());
        model.setPutinType(updateValidate.getPutinType());
        model.setUndertakingDepartment(updateValidate.getUndertakingDepartment());
        model.setConductor(updateValidate.getConductor());
        model.setTaxRate(updateValidate.getTaxRate());
        model.setCostType(updateValidate.getCostType());
        model.setCost(updateValidate.getCost());
        model.setContributionPool(updateValidate.getContributionPool());
        model.setOwnershipDistribution(updateValidate.getOwnershipDistribution());
        model.setHaveCase(updateValidate.getHaveCase());
        model.setDesignatedCountry(updateValidate.getDesignatedCountry());
        model.setBrandType(updateValidate.getBrandType());
        model.setClassQuantity(updateValidate.getClassQuantity());
        model.setQuantity(updateValidate.getQuantity());
        model.setOfficialFee(updateValidate.getOfficialFee());
        model.setAgencyFee(updateValidate.getAgencyFee());
        model.setHirdPartyPayment(updateValidate.getHirdPartyPayment());
        model.setSignedAmount(updateValidate.getSignedAmount());
        model.setInvoiceValue(updateValidate.getInvoiceValue());
        model.setFundsReceived(updateValidate.getFundsReceived());
        model.setPaidupDate(updateValidate.getPaidupDate());
        model.setPlanNumber(updateValidate.getPlanNumber());
        model.setCaseStatus(updateValidate.getCaseStatus());
        model.setCaseLink(updateValidate.getCaseLink());
        model.setRemark(updateValidate.getRemark());
        model.setCaseNameid(updateValidate.getCaseNameid());
        model.setBusinessTypeid(updateValidate.getBusinessTypeid());
        model.setUndertakingDepartmentid(updateValidate.getUndertakingDepartmentid());
        model.setOwnershipDistributionid(updateValidate.getOwnershipDistributionid());
        model.setCostTypeid(updateValidate.getCostTypeid());
        model.setCorrelationTypeid(updateValidate.getCorrelationTypeid());
        model.setIsRegister(updateValidate.getIsRegister());
        model.setIsInvalid(updateValidate.getIsInvalid());
        model.setIsExistingcase(updateValidate.getIsExistingcase());
        model.setIsPapernotice(updateValidate.getIsPapernotice());
        model.setCustomerDocumentNumber(updateValidate.getCustomerDocumentNumber());
        model.setCopyrightType(updateValidate.getCopyrightType());
        model.setCaseFlow(updateValidate.getCaseFlow());
        model.setCountryOfOrigin(updateValidate.getCountryOfOrigin());
        model.setAgency(updateValidate.getAgency());
        model.setProposalForm(updateValidate.getProposalForm());
        model.setIsMaterials(updateValidate.getIsMaterials());
        model.setIsFund(updateValidate.getIsFund());
        model.setInitialPeriod(updateValidate.getInitialPeriod());
        model.setReferenceNumber(updateValidate.getReferenceNumber());
        model.setContractNumber(updateValidate.getContractNumber());
        model.setBudget(updateValidate.getBudget());
        model.setAuthor(updateValidate.getAuthor());
        model.setHomeLocation(updateValidate.getHomeLocation());
        model.setSoftwareAbbreviation(updateValidate.getSoftwareAbbreviation());
        model.setVersionNumber(updateValidate.getVersionNumber());
        model.setSoftwareWorkDescription(updateValidate.getSoftwareWorkDescription());
        model.setDevelopmentCompletionDate(updateValidate.getDevelopmentCompletionDate());
        model.setPublishedStatus(updateValidate.getPublishedStatus());
        model.setHardwareEnvironment(updateValidate.getHardwareEnvironment());
        model.setSoftwareEnvironment(updateValidate.getSoftwareEnvironment());
        model.setProgrammingLanguage(updateValidate.getProgrammingLanguage());
        model.setSourceQuantity(updateValidate.getSourceQuantity());
        model.setFunctionAndArt(updateValidate.getFunctionAndArt());
        model.setHandlingInformation(updateValidate.getHandlingInformation());
        model.setPrincipalDates(updateValidate.getPrincipalDates());
        model.setCustomerTerm(updateValidate.getCustomerTerm());
        model.setInternalWearLife(updateValidate.getInternalWearLife());
        model.setIsStateCompensation(updateValidate.getIsStateCompensation());
        model.setClick(updateValidate.getClick());
        model.setPartOwner(updateValidate.getPartOwner());
        model.setTodonote(updateValidate.getTodonote());
        model.setManageDate(updateValidate.getManageDate());
        model.setCountType(updateValidate.getCountType());
        model.setNumberOfPoints(updateValidate.getNumberOfPoints());
        model.setAddtotalstatepoint(updateValidate.getAddtotalstatepoint());
        model.setRoyaltyDate(updateValidate.getRoyaltyDate());
        model.setWorkPoints(updateValidate.getWorkPoints());
        model.setCreator(updateValidate.getCreator());
        model.setChargeType(updateValidate.getChargeType());
        model.setCurrency(updateValidate.getCurrency());
        model.setSum(updateValidate.getSum());
        model.setAdvancePaymentDate(updateValidate.getAdvancePaymentDate());
        model.setPaymentRequestNumber(updateValidate.getPaymentRequestNumber());
        model.setRequestedDate(updateValidate.getRequestedDate());
        model.setAccountsDate(updateValidate.getAccountsDate());
        model.setInvoiceNumber(updateValidate.getInvoiceNumber());
        model.setChargeName(updateValidate.getChargeName());
        model.setChargeDepict(updateValidate.getChargeDepict());
        model.setChargeDepictfine(updateValidate.getChargeDepictfine());
        model.setExtendedAmount(updateValidate.getExtendedAmount());
        model.setDiscountRate(updateValidate.getDiscountRate());
        model.setCount(updateValidate.getCount());
        model.setParities(updateValidate.getParities());
        model.setCollectingCompanyAccount(updateValidate.getCollectingCompanyAccount());
        model.setCollectionStatus(updateValidate.getCollectionStatus());
        model.setAccountDetails(updateValidate.getAccountDetails());
        model.setSlt(updateValidate.getSlt());
        model.setExternalBillingNumber(updateValidate.getExternalBillingNumber());
        model.setExternalBillingDate(updateValidate.getExternalBillingDate());
        model.setBeddingCondition(updateValidate.getBeddingCondition());
        model.setHandOver(updateValidate.getHandOver());
        model.setExpenseNote(updateValidate.getExpenseNote());
        model.setReductionType(updateValidate.getReductionType());
        model.setActualCurrency(updateValidate.getActualCurrency());
        model.setOfficialDeadline(updateValidate.getOfficialDeadline());
        model.setOurRef(updateValidate.getOurRef());
        model.setRelevantCaseName(updateValidate.getRelevantCaseName());
        model.setCorrelationType(updateValidate.getCorrelationType());
        model.setId(updateValidate.getId());

        // 设置 操作人信息 以及 更新时间
        model.setUpdateUserId(Long.valueOf(LikeAdminThreadLocal.getAdminId()));
        model.setUpdateUserName(LikeAdminThreadLocal.get("username").toString());
        model.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));

        caseContractMapper.updateById(model);
    }

    /**
     * 新建合同案件信息删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        CaseContract model = caseContractMapper.selectOne(
                new QueryWrapper<CaseContract>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        caseContractMapper.updateById(model);
    }

}
